package stdio.costa.imoca.spi;

import java.io.InputStream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.aliyun.openservices.ClientConfiguration;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;

@Service
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class AliyunStorageAdapter implements StorageSpi {
	
	@Value("#{storage['aliyun.oss.access.id']}")
	private String accessId;

	@Value("#{storage['aliyun.oss.access.key']}")
	private String accessKey;

	@Value("#{storage['aliyun.oss.endpoint']}")
	private String endpoint;

	@Value("#{storage['aliyun.oss.bucket.name']}")
	private String bucketName;

	@Value("#{storage['aliyun.oss.publish.domain']}")
	private String publishDomain;
	
	@Override
	@Async
	public void uploadAsynchronously(InputStream file, String mimeType, String uuid) throws Exception {
		uploadSynchronously(file, mimeType, uuid);
	}

	@Override
	public String buildGetUrl(String uuid, int width, int height) {
		// aliyun does not support resize image, and in order to save our host server's brand width, ignore resize request and force app to resize itself
		return new StringBuilder(publishDomain).append(uuid).toString();
	}

	@Override
	public void uploadSynchronously(InputStream file, String mimeType, String uuid) throws Exception {
		ClientConfiguration config = new ClientConfiguration();
		OSSClient client = new OSSClient(endpoint, accessId, accessKey, config);
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentType(mimeType);
		client.putObject(bucketName, uuid, file, metadata);
	}

}
